package 双向环形链表;

import java.util.Iterator;

public class DoublyLinkedListSentinel implements Iterable<Integer>{
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    // 节点类
    private static class Node {
        Node pre;
        int value;
        Node next;

        public Node(Node pre, int value, Node next) {
            this.pre = pre;
            this.value = value;
            this.next = next;
        }
    }


    // 哨兵
    private Node sentinel = new Node(null, -1, null);

    public DoublyLinkedListSentinel() {
        sentinel.pre = sentinel;
        sentinel.next = sentinel;
    }


    // 添加到第一个
    public void addFirst(int value) {
        Node a = sentinel;
        Node b = sentinel.next;
        Node added = new Node(a, value, b);
        a.next = added;
        b.pre = added;
    }


    // 添加到最后一个
    public void addLast(int value) {
        Node a = sentinel;
        Node b = sentinel.pre;
        Node added = new Node(b, value, a);
        b.next = added;
        a.pre = added;
    }

    // 删除最后一个
    public void removeLast() {
        Node remove = sentinel.pre;
        if (remove == sentinel) {
            System.out.println("没元素");
            return;
        }
        Node a = sentinel;
        Node b = remove.pre;
        a.pre = b;
        b.next = a;
    }

    // 删除第一个
    public void removeFirst() {
        Node remove = sentinel.next;
        if (remove == sentinel) {
            System.out.println("没元素");
            return;
        }
        Node a = sentinel;
        Node b = remove.next;
        a.next = b;
        b.pre = a;
    }

    // 根据值删除
    public void removeByValue(int value) {
        // 首先要遍历链表, 找到对应的值
        Node removed = findByValue(value);
        if (removed == null) {
            return;
        }
        Node a = removed.pre;
        Node b = removed.next;
        a.next = b;
        b.pre = a;
    }

    public Node findByValue(int value) {
        Node p = sentinel.next;
        while (p != sentinel) {
            if (p.value == value) {
                return p;
            }
            p = p.next;
        }
        return null;
    }
}
